<script setup lang="ts">
import {sessionListApi, type sessionType} from "@/api/session_list_api";
import {nextTick, reactive, ref} from "vue";
import type {listResponse} from "@/api";
import {Message} from "@arco-design/web-vue";
import F_text from "@/components/common/f_text.vue";
import {dateFormat, dateTimeFormat} from "@/utils/date";
import {IconSend, IconDelete} from "@arco-design/web-vue/es/icon";
import type {sessionListParams} from "@/api/session_list_api";
import {sessionUpdateTitleApi} from "@/api/session_list_api";
import {sessionRemoveApi} from "@/api/session_list_api";
import F_avatar from "@/components/common/f_avatar.vue";
const params = reactive<sessionListParams>({
  type: 1,
  limit: 6,
  page: 1,
})

const data = reactive<listResponse<sessionType>>({
  list: [],
  count: 0,
})


interface ListType {
  date: string
  list: sessionType[]
}

const list = ref<ListType[]>([])

/*
[
{
  date: "一天前",
  list: []
},
{
  date: "两天前",
  list: []
},

]
 */

async function getData() {
  list.value = []
  const res = await sessionListApi(params)
  if (res.code) {
    Message.error(res.msg)
    return
  }
  data.count = res.data.count

  for (const item of res.data.list) {
    const date = dateFormat(item.createdAt)
    // 找这个时间在哪一个对象里面
    const obj = list.value.find((i) => i.date === date)
    if (!obj) {
      // 没有
      list.value.push({
        date: date,
        list: [item]
      })
      continue
    }
    obj.list.push(item)
  }
}

getData()

const checkItem = reactive<sessionType>({
  "id": 9,
  "createdAt": "2024-08-25T08:47:19.24+08:00",
  "userID": 10,
  "roleID": 9,
  "title": "",
  "aiRoleAvatar": "",
  "aiRoleTitle": "go开发助手1",
  "chatLastContent": "",
  "chatCount": 0,
  "chatLastDate": "0001-01-01T00:00:00Z",
  "userNickname": "",
  "userAvatar": ""
})

const title = ref()

const visible = ref(false)

const titleRef = ref()

async function handleSelect(value: string | number | Record<string, any> | undefined, item: sessionType) {
  const val = value as number
  if (val === 1){
    Object.assign(checkItem, item)
    title.value = checkItem.title
    visible.value = true
    nextTick(() => {
      titleRef.value.focus()
    })
  }
  if (val === 2){
    const res = await sessionRemoveApi([item.id])
    if (res.code){
      Message.error(res.msg)
      return
    }
    getData()
    Message.success(res.msg)
  }


}

async function updateSessionTitle() {
  if (checkItem.title === title.value) {
    Message.warning("暂未修改")
    return true
  }
  if (title.value.trim() === "") {
    Message.warning("会话名称不能为空")
    return false
  }
  const res = await sessionUpdateTitleApi({
    sessionID: checkItem.id,
    title: title.value
  })
  if (res.code){
    Message.error(res.msg)
    return false
  }
  Message.success(res.msg)
  visible.value = false
  getData()
  return true
}


</script>

<template>
  <div class="history_view">
    <div class="search">
      <a-input-search @keydown.enter="getData" @search="getData" v-model="params.key"
                      placeholder="搜索会话"></a-input-search>
    </div>
    <a-modal v-model:visible="visible" title="修改会话名称" :on-before-ok="updateSessionTitle">
      <a-input ref="titleRef" placeholder="会话名称" v-model="title"></a-input>
    </a-modal>
    <div class="body" v-if="list.length">
      <div class="date_w" v-for="d in list">
        <div class="date">
          {{ dateFormat(d.date) }}
        </div>
        <div class="list">
          <div class="item" v-for="item in d.list">
            <div class="avatar">
              <f_avatar :size="50" :title="item.aiRoleTitle" :image-url="item.aiRoleAvatar"></f_avatar>
            </div>
            <div class="info">
              <div class="top">
                <f_text class="title">{{ item.title }}</f_text>
                <span class="date">{{ dateTimeFormat(item.createdAt) }}</span>
              </div>
              <f_text class="content" :rows="2">{{ item.chatLastContent }}</f_text>
            </div>
            <div class="actions">
              <router-link :to="{name: 'chat', params: {id: item.id}}">
                <i class="iconfont share icon-24gl-paperPlane"></i>
              </router-link>
              <a-dropdown @select="handleSelect($event, item)" :popup-max-height="false">
                <IconMore style="margin-left: 20px"></IconMore>
                <template #content>
                  <a-doption :value="1">修改名称</a-doption>
                  <a-doption :value="2">删除会话</a-doption>
                </template>
              </a-dropdown>

            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="body" v-else>
      <a-empty></a-empty>
    </div>
    <div class="page" v-if="list.length">
      <a-pagination @change="getData" v-model:current="params.page" show-total :total="data.count" :page-size="params.limit"></a-pagination>
    </div>
  </div>
</template>

<style lang="less">
.history_view {
  .search {
    margin-top: 20px;
    display: flex;
    justify-content: end;

    .arco-input-wrapper {
      width: 200px;
      background-color: transparent;
      border: @f_border;
      border-radius: 50px;
    }
  }

  .body {
    margin-top: 20px;

    .date_w {
      margin-top: 20px;

      .date {
        color: var(--color-text-2);
      }
    }
  }

  .list {
    .item {
      margin-top: 10px;
      height: 80px;
      width: 100%;
      border-radius: 5px;
      border: @f_border;
      display: flex;
      padding: 10px;
      position: relative;

      .avatar {
        width: 80px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .info {
        width: 100%;

        .top {
          display: flex;
          align-items: center;
        }

        .title {
          font-weight: 600;
          max-width: 15rem;
        }

        .date {
          margin-left: 5px;
          font-size: 12px;
          color: var(--color-text-2);
        }
      }

      .content {
        font-size: 12px;
        color: var(--color-text-2);
        width: calc(100% - 280px)
      }

      .actions {
        position: absolute;
        right: 40px;
        top: 50%;
        transform: translateY(-50%);

        svg,.share {
          font-size: 20px;
          cursor: pointer;
          color: var(--color-text-2);
        }

        .delete {
          color: red;
          margin-left: 20px;
        }
      }
    }
  }

  .page {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>